import React, {
    useMemo,
    useState,
    useEffect,
    useRef
} from 'react'
import { Button } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import { BaseButtonProps } from 'antd/lib/button/button'
import storage from '@/utils/storage'
import { USER_INFORMATION } from '@/utils/storage/constant'
import { hasAuth } from '@/framework/utils'


interface IProps extends BaseButtonProps {
    roles?: Array<string>
    url?: string,
    onClick?: () => void,
}

const FetchButton: React.FC<IProps> = (props) => {
    const {
        url,
        roles,
        disabled,
        children,
        onClick,
        ...other
    } = props
    const { roles: userRoles } = storage.getStorage(USER_INFORMATION) || {}
    const [loading, setLoading] = useState<boolean>(false)
    const timer = useRef<any>(null)

    const isAuth = useMemo(() => {
        return roles && hasAuth(roles, userRoles)
    }, [roles])

    useEffect(() => {
        return () => {
            timer.current && clearTimeout(timer.current)
        }
    }, [])

    const handleUlrFetch = () => {
        if (url) {
            setLoading(true)
            // 模拟一下请求数据，按钮进入加载状态，避免频繁请求
            new Promise((resolve) => {
                timer.current && clearTimeout(timer.current)

                timer.current = setTimeout(() => {
                    resolve(1)
                }, 1000)
            }).then(() => {
                setLoading(false)
            })
        }
    }

    const renderButton = () => {
        return (
            <Button
                loading={loading}
                disabled={loading}
                type='primary'
                icon={url ? <SearchOutlined /> : null}
                onClick={() => {
                    handleUlrFetch()
                    onClick && onClick()
                }}
                {...other}
            >{children}</Button>
        )
    }

    // 未启用禁用模式，根据是否有权限进行显示，否则根据权限进行按钮禁用
    if (disabled === undefined) {
        // 不需要权限控制
        if (isAuth === undefined) {
            return (
                <Button
                    type='primary'
                    disabled={disabled}
                    onClick={() => {
                        onClick && onClick()
                    }}
                    {...other}
                >{children}</Button>
            )
        }

        return isAuth ? renderButton() : null
    }

    return isAuth ? renderButton() : (
        <Button
            disabled={disabled}
            type='primary'
            icon={url ? <SearchOutlined /> : null}
            {...other}
        >{children}</Button>
    )
}

export default FetchButton